﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Windows.Forms;
using DAL.Model;
using UI.Helper;

namespace UI.MasterData
{
    public partial class frmProductAttribManager : Form
    {
        private MasterSession _session;

        public frmProductAttribManager()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handle loading data on showing form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmProductAttribManager_Load (object sender, EventArgs e)
        {
            _session = new MasterSession();

            // get data for binding grid.
            _session.ProductAttributes.ToArray();
            var productAttrs = _session.ProductAttributes.Local.ToBindingList();

            dgProductAttrs.DataSource = productAttrs;
            gvProductAttrs.BestFitColumns();
        }

        /// <summary>
        /// Close form without saving changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void spCancel_Click (object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Save changes and close form.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void spSave_Click (object sender, EventArgs e)
        {
            _session.CommitChanges();
            this.Close();
        }

        private void gvProductAttrs_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            var productAttribute = (ProductAttribute)gvProductAttrs.GetRow(gvProductAttrs.FocusedRowHandle);
            // if cannot get current row
            if (productAttribute == null)
            {
                return;
            }

            gvProductAttrs.ClearColumnErrors();

            if (string.IsNullOrEmpty(productAttribute.Code))
            {
                gvProductAttrs.SetColumnError(FormHelper.GetColumn(gvProductAttrs, "Code"), "Nhập mã loại");
                e.Valid = false;
            }
            if (string.IsNullOrEmpty(productAttribute.Name))
            {
                gvProductAttrs.SetColumnError(FormHelper.GetColumn(gvProductAttrs, "Name"), "Nhập tên loại");
                e.Valid = false;
            }
        }
    }
}
